package com.sunseaypw.web;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import com.sunseaypw.web.serverlet.HelloServerlet;
import com.sunseaypw.web.serverlet.MainServerlet;
import com.sunseaypw.web.serverlet.UserServerlet;

import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.annotations.AnnotationConfiguration.ClassInheritanceMap;
import org.eclipse.jetty.plus.webapp.EnvConfiguration;
import org.eclipse.jetty.plus.webapp.PlusConfiguration;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.PathResource;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.FragmentConfiguration;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.webapp.WebXmlConfiguration;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class StartJettyWeb {
    public static void main( String[] args ){
        /*jetty 四元素 connector server handle /threadpool
            
        */
        try{// 启动Jetty    
            // Create and configure a ThreadPool.
            QueuedThreadPool threadPool = new QueuedThreadPool();
            threadPool.setName("server");
            // Create a Server instance.
            Server server = new Server(threadPool);
            // Create a ServerConnector to accept connections from clients.
            ServerConnector connector = new ServerConnector(server);
            connector.setPort(9999);
            // Add the Connector to the Server
            server.addConnector(connector);
            
            ContextHandlerCollection contexts = new ContextHandlerCollection();

            // Set a simple Handler to handle requests/responses.
            // server.setHandler(new AbstractHandler(){
            //     @Override
            //     public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response)
            //     {      
            //         try{
            //             response.setContentType("text/html;charset=utf-8");
            //             response.setStatus(HttpServletResponse.SC_OK);                    
            //             response.getWriter().println("<h1>Hello World3333333</h1>");

            //             // Mark the request as handled so that it
            //             // will not be processed by other handlers.
            //             jettyRequest.setHandled(true);
            //         }catch(Exception ex){
            //             ex.printStackTrace();
            //         }     
            //     }
            // });

            String rootpath = "D:\\PrjRoot\\javaroot\\template\\web-app";            
            WebAppContext wcxt = new WebAppContext();
            //web应用的根目录，含静态资源
            wcxt.setResourceBase(rootpath+"\\src\\main\\webapp");
            /* 不用特意处理，自动会处理WEB-INFO/web.xml */
            //wcxt.setDescriptor(rootpath+"\\src\\main\\webapp\\WEB-INF\\web.xml");   
            /* 不需要特意处理，调试期间vscode/maven会设置classpath，同时也会自动根据serverlet规范自动加载WEB-INFO/classes /lib  */         
            //wcxt.setExtraClasspath(rootpath+"\\target\\classes");
            
            //no web inf for us - so let the scanning know about location of our libraries / classes.
            wcxt.getMetaData().setWebInfClassesResources(Arrays.asList(wcxt.getBaseResource()));
            //wcxt.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/classes/.*");                  
            wcxt.setContextPath("/");
            //==============设置classloader
            wcxt.setClassLoader(Thread.class.getClassLoader());
            wcxt.setParentLoaderPriority(true);    
            contexts.addHandler(wcxt);    
                        
            ServletContextHandler main = new ServletContextHandler(server, "/test", true, false);
            main.addServlet(new ServletHolder(new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
                        throws ServletException, IOException {
                    resp.getWriter().write("main");
                }
            }), "/main");
            contexts.addHandler(main);
            
            ServletContextHandler sub = new ServletContextHandler();
            sub.setContextPath("/sub");
            sub.addServlet(MainServerlet.class, "/hello");
            contexts.addHandler(sub);

            contexts.addHandler(new DefaultHandler());
            server.setHandler(contexts);            
            // Start the Server so it starts accepting connections from clients.
            server.start();
            server.join();            
        
        }catch(Exception ex){
            System.out.println(ex.toString());
        }
    }
    
}
